package org.pupil.socket.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.pupil.annotation.RpcService;
import org.pupil.common.URL;
import org.pupil.common.constants.Register;
import org.pupil.register.RegistryFactory;
import org.pupil.register.RegistryService;
import org.pupil.service.HelloService;
import org.pupil.socket.codec.RpcDecoder;
import org.pupil.socket.codec.RpcEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Description: 服务提供方1
 * @Author: pupil
 * @Date: 2024/07/09 下午 4:31
 */
public class Server {

    private Logger logger = LoggerFactory.getLogger(Server.class);

    private String host; // ip地址

    private final Integer port; // 监听端口

    public Server(Integer port) {
        this.port = port;

        // 自动判断获取服务提供方启动时网络ip地址
        InetAddress inetAddress = null;
        try {
            inetAddress = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        host = inetAddress.getHostAddress();
    }

    // 启动服务提供方
    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new RpcEncoder())
                                    .addLast(new RpcDecoder())
                                    .addLast(new ServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            serverBootstrap.bind(port).sync().channel().closeFuture().sync();
            logger.info("rpc server 启动: ", port);

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    // 进行服务注册
    public void registerBean(Class clazz) throws Exception {
        // 创建服务提供方资源定位符
        final URL url = new URL(host, port);
        if (!clazz.isAnnotationPresent(RpcService.class)) {
            throw new Exception(clazz.getName() + "没有注解 RpcService ");
        }
        final RpcService rpcService = (RpcService) clazz.getAnnotation(RpcService.class);
        url.setServiceName(clazz.getName());
        url.setVersion(rpcService.version());
        final RegistryService registryService = RegistryFactory.get(Register.ZOOKEEPER);
        registryService.register(url);

    }

    public static void main(String[] args) throws Exception {
        final Server server = new Server(8081);
        server.registerBean(HelloService.class);
        server.run();
    }
}
